package com.mt.restaurant.service.sale.impl;

import com.mt.restaurant.dao.sale.AddressDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.restaurant.entity.sale.Address;
import com.mt.restaurant.service.sale.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
@Transactional
public class AddressServiceBean extends BaseService implements AddressService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private AddressDao addressDao;

	@Resource
	private RedisTemplate<String, List<Address>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询地址集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findAddresss(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindAddresss(pageDTO);
		List<Address> addressDTOS = this.addressDao.findAddresss(pageDTO);
		Long totalCount = this.addressDao.findAddressTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(addressDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部地址集合
	 *
	 */
	@Override
	public List<Address> findAllAddresss(){
		return this.addressDao.findAllAddresss();
	}

	/**
	 * 查询所有地址集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Address> findAllAddresssWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllAddresssWithIdName();
		return this.addressDao.findAllAddresssWithIdName();
	}

	/**
	 * 根据名称查询地址集合(只提取ID 和 Name)
	 *
	 * @param addressName 名称
	 */
	@Override
	public List<Address> findAddresssWithIdNameByName(String addressName){
		//TODO:请在此校验参数的合法性
		this.validateFindAddresssWithIdNameByName(addressName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Address_where_addressName_" + addressName);
		List<Address> addresss = new ArrayList<>();
		if (keys.isEmpty()) {
		addresss = this.addressDao.findAddresssWithIdNameByName(addressName);
		redisTemplate.opsForValue().set("searchData:Address_where_addressName_" + addressName, addresss, 30, TimeUnit.DAYS);
		} else {
		addresss = redisTemplate.opsForValue().get("searchData:Address_where_addressName_" + addressName);
		}
		return addresss;
	}

	/**
	 * 根据ID查询指定的地址(只提取ID 和 Name)
	 *
	 * @param addressId Id
	 */
	@Override
	public Address findAddresssWithIdNameById(Long addressId){
		//TODO:请在此校验参数的合法性
		this.validateFindAddresssWithIdNameById(addressId);
		return this.addressDao.findAddresssWithIdNameById(addressId);
	}

	/**
	 * 根据ID查询指定的地址
	 *
	 * @param addressId Id
	 */
	@Override
	public Address findAddress(Long addressId){
		//TODO:请在此校验参数的合法性
		this.validateFindAddress(addressId);
		return this.addressDao.findAddress(addressId);
	}

	/**
	 * 根据ID查询指定的地址(包含外键)
	 *
	 * @param addressId Id
	 */
	@Override
	public Address findAddressWithForeignName(Long addressId){
		//TODO:请在此校验参数的合法性
		this.validateFindAddressWithForeignName(addressId);
		return this.addressDao.findAddressWithForeignName(addressId);
	}

	/**
	 * 新增地址
	 *
	 * @param address 实体对象
	 */
	@Override
	public Address saveAddress(Address address){
		//TODO:请在此校验参数的合法性
		this.validateSaveAddress(address);
		//TODO:填充公共参数
		this.setSavePulicColumns(address);
		Long rows = this.addressDao.saveAddress(address);
		if(rows != 1)
		{
			String error = "新增保存地址出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return address;
	}

	/**
	 * 更新地址
	 *
	 * @param address 实体对象
	 */
	@Override
	public Address updateAddress(Address address){
		//TODO:请在此校验参数的合法性
		this.validateUpdateAddress(address);
		Long rows = this.addressDao.updateAddress(address);
		if(rows != 1)
		{
			String error = "修改保存地址出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return address;
	}

	/**
	 * 根据ID删除地址
	 *
	 * @param addressId ID
	 */
	@Override
	public void deleteAddress(Long addressId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteAddress(addressId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Address.class, addressId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.addressDao.deleteAddress(addressId);
		if(rows != 1){
			String error = "删除地址出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	//TODO:---------------验证-------------------

	private void validateFindAddresss(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateFindAddresssWithIdNameByName(String addressName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}


	private void validateFindAllAddresssWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateFindAddresssWithIdNameById(Long addressId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateFindAddress(Long addressId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateFindAddressWithForeignName(Long addressId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateSaveAddress(Address address) {
	//不为空判断
	if (address.getEid() != null || address.getCreatorId() != null || address.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateUpdateAddress(Address address) {
	//不为空判断
	if (address.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.addressDao.findAddressTotalCount(PageDTO.create(Address.FIELD_ID, address.getEid())) == 0) {
	throw new BusinessException("修改的地址 " + address.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	private void validateDeleteAddress(Long addressId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateAddress()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
